package com.lotso.web.common.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.Getter;
import lombok.Setter;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.nio.charset.Charset;

/**
 * ClassName: PdfUtil
 * Description:
 * Date: 2019/5/8 10:09 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class PdfUtil {

    /**
     * 生成一个PDF文件
     *
     * @param fileName
     * @param content
     * @throws Exception
     */
    public static void create(String fileName, String content) throws Exception {
        // 1-创建文本对象 Document
        Document document = new Document();

        // 2-初始化 pdf输出对象 PdfWriter
        PdfWriter.getInstance(document, new FileOutputStream(fileName));

        // 3-打开 Document
        document.open();

        // 4-往 Document 添加内容
        document.add(new Paragraph(content, getChineseFont()));

        // 5-关闭 Document
        document.close();
    }

    /**
     * 创建带有属性的PDF
     *
     * @param fileName
     * @param pdfContent
     * @throws Exception
     */
    public static void create(String fileName, PdfContent pdfContent) throws Exception {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        // 设置属性
        document.addAuthor(pdfContent.getAuthor());
        document.addCreator(pdfContent.getCreator());
        document.addTitle(pdfContent.getTitle());
        document.addSubject(pdfContent.getSubject());
        document.addCreationDate();


        document.add(new Paragraph(pdfContent.getContent(), getChineseFont()));
        document.close();
        writer.close();
    }


    /**
     * 根据模板生成PDF
     *
     * @param fileName     生成的文件
     * @param templateName 模板文件
     * @param data
     * @throws Exception
     */
    public static void create(String fileName, String templateName, Object data) throws Exception {

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        String template = getContent(templateName, data);
        XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(template.getBytes()), Charset.forName("UTF-8"), new AsianFontProvider());

        document.close();
        writer.close();
    }

    /**
     * 支持中文
     */
    static class AsianFontProvider extends XMLWorkerFontProvider {

        private final static String C_FONT_NAME = "STSongStd-Light";
        private final static String C_FONT_ENCODING = "UniGB-UCS2-H";


        public Font getFont(float size, final int style) {
            return this.getFont(C_FONT_NAME, C_FONT_ENCODING, size, style);
        }

        @Override
        public Font getFont(final String fontName, String encoding, float size, final int style) {
            try {
                BaseFont baseFont = BaseFont.createFont(C_FONT_NAME, C_FONT_ENCODING, BaseFont.NOT_EMBEDDED);
                return new Font(baseFont, size, style);
            } catch (Exception e) {
            }
            return super.getFont(fontName, encoding, size, style);
        }
    }

    /**
     * 中文字体支持
     *
     * @return
     * @throws Exception
     */
    private static Font getChineseFont() {
        return new AsianFontProvider().getFont(12, Font.NORMAL);
    }

    /**
     * 填充模板
     *
     * @param fileName
     * @param data
     * @return
     * @throws Exception
     */
    private static String getContent(String fileName, Object data) throws Exception {
        Configuration config = new Configuration(Configuration.VERSION_2_3_28);
        config.setDefaultEncoding("UTF-8");
        config.setClassLoaderForTemplateLoading(PdfUtil.class.getClassLoader(), "/");
        config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        config.setLogTemplateExceptions(true);
        Template template = config.getTemplate(fileName, "UTF-8");

        return FreeMarkerTemplateUtils.processTemplateIntoString(template, data);
    }


    @Setter
    @Getter
    static class PdfContent {
        /**
         * 作者
         */
        private String author;
        /**
         * 创建者（应用程序）
         */
        private String creator;
        /**
         * 标题
         */
        private String title;

        /**
         * 主题
         */
        private String subject;
        /**
         * 内容
         */
        private String content;

    }
}
